package com.soywer.rpc.rpc08;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianOutput;
import com.soywer.rpc.common.User;

/**
 * 功能描述：
 * hessian序列化的基本使用
 * @author 18065916_李猛
 * @since 2021/3/11
 */
public class HelloHessian {

    public static void main(String[] args) throws Exception {
        User u = new User(1,"zhangsan");
        byte[] bytes = serialize(u);
        System.out.println(bytes.length);
        User u1 = (User)deserialize(bytes);
        System.out.println(u1);

        System.out.println(u.hashCode());
        System.out.println(u1.hashCode());
    }

    //hessian对象序列化字节数组
    public static byte[] serialize(Object o) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Hessian2Output output = new Hessian2Output(baos);
        output.writeObject(o);
        output.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        output.close();
        return bytes;
    }

    //hessian字节数组反序列化成对象
    public static Object deserialize(byte[] bytes) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        Hessian2Input input = new Hessian2Input(bais);
        Object o = input.readObject();
        bais.close();
        input.close();
        return o;
    }
}
